package com.aispeech.testcustom.view;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aispeech.testcustom.R;
import com.aispeech.testcustom.bean.WakeupInfoBean;
import com.aispeech.testcustom.i.GetWakeupListener;
import com.aispeech.testcustom.utils.TestNode;
import com.aispeech.testcustom.utils.UiUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MissWakeupActivity extends AppCompatActivity implements GetWakeupListener {

    private static final int UPDATE_SECOND = 1;
    private static final int UPDATE_MINUTE = 2;
    private static final int UPDATE_HOUR   = 3;
    private static final int UPDATE_DAY    = 4;

    private Button mBtnStart, mBtnWakeInfo;
    private TextView mTvDay, mTvHour, mTvMinute, mTvSecond;
    private TextView mTvMajorCount;
    private TextView mTvshortcutCount;
    private TextView mTvCommandCount;

    public  boolean isTesting           = false;//是否开始误唤醒测试
    private int     majorWakeupTimes    = 0;//主误唤醒次数
    private int     shortcutWakeupTimes = 0;//自定义误唤醒次数
    private int     CommandWakeupTimes  = 0;//系统快捷误唤醒次数
    private long    startTime           = 0;
    private long    endTime             = 0;

    private String majorWakeup;//获取主唤醒词


    long trigger  = 0;//什么时候开始
    long interval = 1;//间隔触发时间,默认1s

    ScheduledExecutorService pool;//定时器

    private ListView        mLvWake;//每唤醒一次,记录时间和音频
    private List<String>    mlist;
    private MsWakeupAdapter msWakeupAdapter;

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_SECOND:
                    mTvSecond.setText((Integer) msg.obj + "");
                    break;
                case UPDATE_MINUTE:
                    mTvMinute.setText((Integer) msg.obj + "");
                    break;
                case UPDATE_HOUR:
                    mTvHour.setText((Integer) msg.obj + "");
                    break;
                case UPDATE_DAY:
                    mTvDay.setText((Integer) msg.obj + "");
                    break;
            }
        }
    };


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            MissWakeupActivity.this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_miss_wakeup);

        UiUtils.showBack4ActionBar(this, "误唤醒测试");
        //将TestNode启动 , 捕获快捷唤醒和录音数据
        TestNode.getInstance().start();
        //TestNode.getInstance().registerWakeupListener(this);

        initView();
        initEvent();

        mlist = new ArrayList<>();
        msWakeupAdapter = new MsWakeupAdapter();
        mLvWake.setAdapter(msWakeupAdapter);
    }

    private void initEvent() {
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isTesting = !isTesting;
                mBtnStart.setText(isTesting ? "停止测试" : "开始测试");
                startTime = System.currentTimeMillis();
                majorWakeup = TestNode.getInstance().majorWakeup;

                if (isTesting) {
                    //注册aios状态监听
                    Log.d("test", "开始测试误唤醒!!");

                    //开始测试前 , 将之前的listview清空
                    mlist.clear();
                    msWakeupAdapter.notifyDataSetChanged();

                    //开始记时
                    timeControl();
                    if (null == TestNode.getInstance().wakeupListener) {
                        TestNode.getInstance().registerWakeupListener(MissWakeupActivity.this);
                    }
                } else {

                    endTime = System.currentTimeMillis();
                    //关闭监听
                    Log.d("test", "误唤醒测试结束!!");
                    //                    majorWakeupTimes = 0;
                    //                    shortcutWakeupTimes = 0;
                    //                    CommandWakeupTimes = 0;

                    //结束记时
                    timeControl();

                    pool.shutdown();
                    TestNode.getInstance().unRegisterWakeupListener();
                }


            }
        });

        mBtnWakeInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null == TestNode.getInstance().wakeupInfoBean) {
                    Toast.makeText(getBaseContext(), "请先唤醒一次吧!", Toast.LENGTH_SHORT).show();
                } else {
                    //在listview中显示
                    WakeupInfoBean wkbean = TestNode.getInstance().wakeupInfoBean;

                    mlist.add("confidence : " + wkbean.getConfidence());
                    mlist.add("frame : " + wkbean.getFrame());
                    mlist.add("lib_version : " + wkbean.getLib_version());
                    mlist.add("status : " + wkbean.getStatus());
                    mlist.add("vad_version : " + wkbean.getVad_version());
                    mlist.add("version : " + wkbean.getVersion());
                    mlist.add("wakeupWord : " + wkbean.getWakeupWord());

                    if (wkbean.getWords()!=null){

                        if (wkbean.getWords().size() > 0) {
                            Set<Map.Entry<String, Float>> entries = wkbean.getWords().entrySet();
                            for (Map.Entry<String,Float> en:entries){
                                mlist.add(en.getKey()+":"+en.getValue());
                            }
                        }
                    }
                    msWakeupAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    int s = 0;
    int m = 0;
    int h = 0;
    int d = 0;

    //记录测试时长和显示
    private void timeControl() {
        if (isTesting) {
            pool = Executors.newScheduledThreadPool(1);
            //开始记时
            pool.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    s++;
                    if (s >= 60) {
                        m++;
                        s = 0;

                        Message mmsg = Message.obtain();
                        mmsg.what = UPDATE_MINUTE;
                        mmsg.obj = m;
                        mhandler.sendMessage(mmsg);

                        if (m >= 60) {
                            h++;
                            m = 0;

                            Message hmsg = Message.obtain();
                            hmsg.what = UPDATE_HOUR;
                            hmsg.obj = h;
                            mhandler.sendMessage(hmsg);

                            if (h >= 24) {
                                d++;
                                h = 0;

                                Message dmsg = Message.obtain();
                                dmsg.what = UPDATE_DAY;
                                dmsg.obj = d;
                                mhandler.sendMessage(dmsg);
                            }
                        }
                    }

                    Message smsg = Message.obtain();
                    smsg.what = UPDATE_SECOND;
                    smsg.obj = s;
                    mhandler.sendMessage(smsg);
                }
            }, trigger, interval, TimeUnit.SECONDS);
        } else {
            //结束记时
            Log.d("test", "停止记时");
        }
    }


    private void initView() {
        mBtnStart = (Button) findViewById(R.id.btn_mswk_start);
        mBtnWakeInfo = (Button) findViewById(R.id.btn_mswk_wkinfo);

        mTvDay = (TextView) findViewById(R.id.tv_mswk_day);
        mTvHour = (TextView) findViewById(R.id.tv_mswk_hour);
        mTvMinute = (TextView) findViewById(R.id.tv_mswk_minute);
        mTvSecond = (TextView) findViewById(R.id.tv_mswk_second);
        mTvMajorCount = (TextView) findViewById(R.id.tv_mswk_major_count);
        mTvshortcutCount = (TextView) findViewById(R.id.tv_mswk_shortcut_count);
        mTvCommandCount = (TextView) findViewById(R.id.tv_mswk_command_count);

        mLvWake = (ListView) findViewById(R.id.lv_mswk_wakeup_info);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("test", "onDestroy: ");
        if (isTesting) {
            TestNode.getInstance().unRegisterWakeupListener();
            pool.shutdown();
        }

        TestNode.getInstance().stop();
    }

    @Override
    public void wakeupCallBack(String wakeupType, String wakeupWord) {
        if (isTesting) {
            //唤醒回调
            Log.d("test", "wakeupCallBack() called with: " + "wakeupType = [" + wakeupType + "], " +
                    "wakeupWord = [" + wakeupWord + "]");

            if ("wakeup.result".equals(wakeupType)) {
                updateUIShow(1, wakeupWord);
            } else if ("sdk.customize.shortcut.wakeup.effect".equals(wakeupType)) {
                updateUIShow(2, wakeupWord);
            } else if ("wakeup.command".equals(wakeupType)) {
                updateUIShow(3, wakeupWord);
            }
        }
    }

    private void updateUIShow(final int type, final String name) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (type) {
                    case 1:
                        mTvMajorCount.setText("主唤醒: " + ++majorWakeupTimes);
                        mlist.add(String.format("%1$tF %1$tT", new Date()) + "--" + name);
                        msWakeupAdapter.notifyDataSetChanged();
                        break;
                    case 2:
                        mTvshortcutCount.setText("自定义快捷唤醒: " + ++shortcutWakeupTimes);
                        mlist.add(String.format("%1$tF %1$tT", new Date()) + "--" + name);
                        msWakeupAdapter.notifyDataSetChanged();
                        break;
                    case 3:
                        mTvCommandCount.setText("系统指令唤醒: " + ++CommandWakeupTimes);
                        mlist.add(String.format("%1$tF %1$tT", new Date()) + "--" + name);
                        msWakeupAdapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }

    class MsWakeupAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (null != mlist) {
                return mlist.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int i) {
            if (null != mlist) {
                return mlist.get(i);
            }
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder = null;
            if (null == view) {
                view = View.inflate(MissWakeupActivity.this, R.layout.item_miss_wakeup, null);
                holder = new Holder();
                view.setTag(holder);
                holder.tvMsWakeTime = (TextView) view.findViewById(R.id.item_ms_time);
            } else {
                holder = (Holder) view.getTag();
            }

            holder.tvMsWakeTime.setText(mlist.get(i));
            return view;
        }
    }

    private class Holder {
        TextView tvMsWakeTime;
    }


}
